﻿using RockBus.DataContracts;
using RockBus.Logging.Interfaces;
using System;
using System.Linq;
using System.Reflection;
using System.ServiceModel;
using System.ServiceModel.Configuration;

namespace RockBus.Hosting
{
    public class SelfHostedDynamicServiceHost<TService> : ReceivePortServiceHostBase<TService>
    {
        public SelfHostedDynamicServiceHost(ILogger logger, ReceivePortInfo receivePortInfo)
            : base(logger, receivePortInfo.ReceiveEndpointInfo, receivePortInfo.GetPublisherReceivePortInfo())
        {
            this.Logger.LogInfo(MethodBase.GetCurrentMethod(), "Creating SelfHostedDynamicServiceHost on original address {0}", receivePortInfo.ReceiveEndpointInfo.Address);

            var baseAddresses = new UriSchemeKeyedCollection();
            foreach (BaseAddressElement baseAddressElement in this.TemplateServiceElement.Host.BaseAddresses)
            {
                baseAddresses.Add(new Uri(baseAddressElement.BaseAddress));
            }

            this.ReceivePortBaseAddresses = baseAddresses.ToArray();

            this.InitializeDescription(typeof(TService), new UriSchemeKeyedCollection());
        }
    }
}